package com.hl.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {
	
	private Connection connection;
	/**
	 * 要求用户在使用dao层方法之前一定要传入一个数据库连接
	 * @param connection
	 */
	public BaseDao(Connection connection) {
		this.connection = connection;
	}
	/**
	 * 增删改方法
	 * 
	 * @param sql
	 * @param obj
	 * @return
	 */
	public int executeUpdate(String sql, Object... obj) {
		// 1:获取数据库连接
		Connection conn = this.connection;
		PreparedStatement pstmt = null;
		int num = -1;
		try {
			// 2:获取数据库操作对象pstmt
			pstmt = conn.prepareStatement(sql);
			// 3:传入参数
			for (int i = 0; i < obj.length; i++) {
				pstmt.setObject(i + 1, obj[i]);
			}
			// 4:执行方法
			num = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return num;
	}

	/**
	 * 获取一张表的数据
	 * 
	 * @param sql
	 *            sql语句
	 * @param obj
	 *            填入的参数
	 * @return 整张表的数据
	 */
	public ResultSet executeQuery(String sql, Object... obj) {
		// 1:获取数据库连接
		Connection conn = this.connection;
		// 2:准备rs对象
		ResultSet rs = null;
		PreparedStatement pstmt =null;
		try {
			pstmt = conn.prepareStatement(sql);
			// 3:传入数据库参数
			for (int i = 0; i < obj.length; i++) {
				pstmt.setObject(i + 1, obj[i]);
			}
			// 4:执行sql方法
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 获取单个数据
	 * @param sql sql语句
	 * @param obj 参数
	 * @return 单个数据
	 */
	public Object executeObject(String sql, Object... obj) {
		// 1:获取数据库连接
		Connection conn = this.connection;
		// 2:准备ResultSet对象
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		Object object = null;
		try {
			pstmt = conn.prepareStatement(sql);
			// 3:循环填入数据
			for (int i = 0; i < obj.length; i++) {
				pstmt.setObject(i + 1, obj[i]);
			}
			// 4:ִ执行Sql语句
			rs = pstmt.executeQuery();
			while (rs.next()) {
				object = rs.getObject(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return object;
	}
}
